package com.ypc.webdemo.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author yinpengcheng
 * @Date 2023/7/24
 */
@Slf4j
@Component
public class SpringBeanUtil implements ApplicationContextAware {
    private static ApplicationContext context;
    private static DefaultListableBeanFactory beanFactory;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
        //将applicationContext转换为ConfigurableApplicationContext
        ConfigurableApplicationContext configurableApplicationContext = (ConfigurableApplicationContext) applicationContext;
        // 获取bean工厂并转换为DefaultListableBeanFactory
        beanFactory = (DefaultListableBeanFactory) configurableApplicationContext.getBeanFactory();
    }

    public static void registerBean(Class<?> clazz, String beanName) {
        BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(clazz);
        beanFactory.registerBeanDefinition(beanName, beanDefinitionBuilder.getBeanDefinition());
        log.info("------ register bean [{}],Class [{}] success.", beanName, clazz);
    }

    public static void removeBean(String beanName) {
        if (!beanFactory.containsBeanDefinition(beanName)) {
            return;
        }
        beanFactory.removeBeanDefinition(beanName);
        log.info("------ remove bean [{}] success.", beanName);
    }

    public static Object getBean(String beanName) {
        return context.getBean(beanName);
    }

    public static <T> T getBean(Class<T> clazz) {
        return context.getBean(clazz);
    }

    public static <T> Map<String, T> getBeans(Class<T> clazz) {
        return context.getBeansOfType(clazz);
    }
}
